package com._5704.website.util;

import com._5704.website.service.ServiceImpl.UserServiceImpl;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

@Component
public class JwtUtil {
    @Resource
    private UserServiceImpl userService;

    // 存储静态的自己，以便调用注入的类
    private static JwtUtil jwtUtil;
    // 过期时间5小时
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
    // 密钥
    private static final String SECRET = "123.456.789";
    // 算法加密
    private static final Algorithm algorithm = Algorithm.HMAC256(SECRET);
    /**
     * 创建token
     * @param userPhone 用户name，我们使用id
     * @return 返回token
     */
    public static String createJwt(String userPhone) {
        Date date = new Date(System.currentTimeMillis() +EXPIRE_TIME);
        String token = JWT.create()
                .withClaim("userPhone",userPhone)
                .withClaim("time",new Date())
                .withExpiresAt(date)//设置过期时间
                .sign(algorithm);//签名
        return token;
    }

    /**
     * 验证token
     * @param token 传入token
     * @return
     */
    public static boolean verify(String token){
        try {
            // 解密，传入算法
            JWT.require(algorithm).build().verify(token);
            // 若token创建时间早于最近登陆时间，说明token废弃
            Date tokenCreateTime = getCreateTime(token);
            Date lastLoginTime = jwtUtil.userService.getUser(getUserId(token)).getLastLoginTime();
            if (lastLoginTime == null || tokenCreateTime == null){
                throw new JWTVerificationException("过期");
            }
            if (lastLoginTime.after(tokenCreateTime)){
                throw new JWTVerificationException("过期");
            }

            return true;

        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 通过token获取用户ID
     * @param token 传入token
     * @return
     */
    public static String getUserId(String token){
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("userPhone").asString();
    }

    /**
     * 获取创建时间
     * @param token 传入token
     * @return
     */
    public static Date getCreateTime(String token){
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("time").asDate();
    }

    /**
     * 初始化静态类，可以使注入service等
     */
    @PostConstruct
    private void init() {
       jwtUtil = this;
       jwtUtil.userService = this.userService;
    }

}
